import MapApi from "../api/MapApi";
import VillageApi from "../api/VillageApi";
import { Army } from "../entity/Army";
import { BManager } from "../entity/BManager";
import { Building } from "../entity/Buildings";
import { Events } from "../entity/Events";
import { EventManager } from "../event/EventManager";
import { EventType, raceName, raceType } from "../settings/const";
import { UIManager } from "./UIManager";

export class UserInfo {
    private static _instance: UserInfo;

    static get instance(): UserInfo {
        if (this._instance == null) {
            this._instance = new UserInfo();
        }

        return this._instance
    }

    public get bList(): BManager[] {

        return this.villageData.bManager.bList
    }

    public get buildings(): BManager[] {
        let list = this.villageData.bManager.bList
        return list.slice(18)
    }

    public get resource(): BManager[] {
        let list = this.villageData.bManager.bList
        return list.slice(0, 18)
    }

    public get eventList(): Events[] {
        let list: Events[] = []
        
        for(let e of this.villageData.eventList) {
            list.push(Events.createByObj(e))
        }

        return list
    }

    public get diamond(): number {
        return this.villageData.user.diamond
    }

    public set diamond(num:number){
        this.villageData.user.diamond = num
    }

    public get race(): number {
        return this.villageData.user.uInfo.race
    }

    public get raceName():string {

        return raceName[this.race]
    }

    public get config(): {Output:number,Speed:number, exchange:number}{
        return this.villageData.config
    }

    public get speed():number{
        return this.config.Speed
    }

    public get isMainVillage():boolean {
        return this.villageData.curVid == this.villageData.curVillage
    }

    public get traderNum():number{
        return this.villageData.traderNum
    }
    public get traderNumCurrent():number{
        return this.villageData.traderNumCurrent
    }
    public set traderNumCurrent(val){
        this.villageData.traderNumCurrent = val
    }

    public get traderPacket():number{
        return this.villageData.traderPacket
    }

    public get soldiersInList():Army[]{
        return this.villageData.soldiersInList
    }
    public get soldiersInNotArrivedList():Army[]{
        return this.villageData.soldiersInNotArrivedList
    }
    public get soldiersOutList():Army[]{
        return this.villageData.soldiersOutList
    }
    public get soldiersOutNotArrivedList():Army[]{
        return this.villageData.soldiersOutNotArrivedList
    }

    public get isFoodIncrease():boolean{
        return (this.villageData.res.food_output - this.villageData.res.parent.Consume) > 0
    }

    /**获取服务器的实时时间 */
    get serverTime():number{
        return new Date().getTime() + this.offsetTime - 2000
    }

    /**时间差，s(服务器时间) -  c(客户端时间) = offset
     * c = s - offset
     * s = c + offset
     */
    public offsetTime:number = 0

    public zone: any;

    public villageData: any; // 当前村庄的数据
    public homeZoneData: any; // 当前村庄坐标位置数据
   

    /**
     * 刷新村庄数据
     * @returns 
     */
    async refreshVillageDetail() {
        await UIManager.instance.showLoading()
        let res = await VillageApi.query()
        UIManager.instance.closeLoading()
        console.log('refreshVillageDetail:', res.data)
        this.villageData = res.data

         // 算出时间差，
         this.offsetTime = res.data.serverTime - new Date().getTime()
         console.log('offsetTime:', this.offsetTime)

        EventManager.instance.emit(EventManager.EventType.GetVillageDetail, this.villageData)
        return this.villageData
    }
    /**
     * 切换村庄，并获取村庄数据，
     * @param zoneId 
     * @returns 
     */
    async changeVillage(zoneId:number){
        await UIManager.instance.showLoading()
        let res = await VillageApi.query(zoneId)
        UIManager.instance.closeLoading()
        console.log('changeVillage:', res.data)
        
        this.villageData = res.data
        

        // EventManager.instance.emit(EventManager.EventType.GetVillageDetail, this.villageData)
        return this.villageData
    }
    

    /**
     * 删除一个事件event
     * @param e 
     */
    public removeEvent(e: Events) {
        if(!e){
            return
        }

        for (let i = this.eventList.length - 1; i >= 0; i--) {
            
            if (e.eHandle == this.eventList[i].eHandle) {
                this.eventList.splice(i, 1)
            }
        }
    }
    
    /**根据uid查找 BMananger */
    getBManage(uid: number): BManager {
       
        return BManager.getBManage(uid)
    }

     /**根据gid(id)查找 BMananger */
    getBManageById(gid:number):BManager{
        
        return BManager.getBManageById(gid)
    }

    /**
   * 获取外城忙碌的工人
   */
    getOuterWorker(): Building[] {
        let list: Building[] = []
        for (let item of this.eventList) {
            if (item.eType == EventType.advBuild) {
                let uid = parseInt(item.eParam)
                if (uid <= 18) {
                    let bm: BManager = this.getBManage(uid)
                    let building =Building.createBuildingByBManager(bm)
                    building.desc = '建造中'
                    list.push(building)
                }
            }
        }

        return list
    }
    /**
     * 获取内城忙碌的工人
     */
    getInnerWorker(): Building[] {
        let list: Building[] = []
        for (let item of this.eventList) {
            if (item.eType == EventType.advBuild) {
                let uid = parseInt(item.eParam)
                if (uid > 18) {
                    let bm: BManager = this.getBManage(uid)
                    let building =Building.createBuildingByBManager(bm)
                    building.desc = '建造中'
                    list.push(building)
                }
            }
        }
        return list
    }
    /**
     * 获取空闲的工人
     */
    getIdleWorker(): Building[] {
        let outer = this.getOuterWorker()
        let inner = this.getInnerWorker()

        let count = 0
        if (this.race == raceType.Rome) {
            count = 3
        } else {
            count = 2
        }

        let idleNum = count - outer.length - inner.length

        let list: Building[] = []
        for (let i = 0; i < idleNum; i++) {
            let b = new Building()
            b.id = 0
            b.name = '建筑工人'
            b.desc = '空闲中'
            list.push(b)
        }

        return list
    }
    /**
     * 获取忙碌的拆除工人
     */
    getRemoveWorker(): Building[] {
        let list: Building[] = []
        for (let item of this.eventList) {
            if (item.eType == EventType.destroy) {
                let uid = parseInt(item.eParam)

                let bm: BManager = this.getBManage(uid)
                let building =Building.createBuildingByBManager(bm)
                building.desc = '拆除中'
                list.push(building)

            }
        }
        return list
    }
    /**
     * 获取空闲的拆除工人
     */
    getIdleRemoveWorker(): Building[] {
        let idle = []

        let list = this.getRemoveWorker()
        
        if(list.length == 0){
            let b = new Building()
            b.id = 0
            b.name = '拆除工人'
            b.desc = '空闲中'
            idle.push(b)
        } 
        return idle
    }
}


